package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"social-app/models"
	"social-app/pkg/err_msg"
	"social-app/pkg/jwt_token"
	"social-app/pkg/response"
	"social-app/pkg/utils"
	"strconv"
	"time"
)

type DynamicReplyController struct{}

func (d DynamicReplyController) Reply(c *gin.Context) {
	type reqParams struct {
		DynamicId int    `json:"dynamic_id" binding:"required"`
		Content   string `json:"content" binding:"required,max=60"`
	}
	msg := map[string]string{
		"DynamicId.required": "动态ID不能为空",
		"Content.required":   "评论内容不能为空",
		"Content.max":        "评论内容不能超过60个字符",
	}

	var params reqParams
	if err := c.ShouldBind(&params); err != nil {
		panic(err_msg.TranslateParamsErr(err, msg))
	}

	userId := jwt_token.GetUserId(c)

	reply, err := models.CreateDynamicReply(userId, params.DynamicId, params.Content)
	if err != nil {
		panic("评论失败")
	}
	_ = models.DynamicReplyInc(params.DynamicId)
	type responseSuccess struct {
		ReplyId int `json:"reply_id"`
	}
	response.Success(c, "评论成功", &responseSuccess{
		ReplyId: reply.Id,
	})
}

func (d DynamicReplyController) GetList(c *gin.Context) {
	dynamicIdStr := c.Param("id")
	dynamicId, _ := strconv.Atoi(dynamicIdStr)

	type reqParams struct {
		Page    int    `form:"page" binding:"required,min=1"`
		Limit   int    `form:"limit" binding:"required,min=1,max=100"`
		OrderBy string `form:"order_by" binding:"omitempty,oneof=create_time"`
		Desc    string `form:"desc" binding:"omitempty,oneof=desc asc"`
	}

	var params reqParams
	if err := c.ShouldBindQuery(&params); err != nil {
		panic(err_msg.TranslateParamsErr(err, nil))
	}
	if params.OrderBy == "" {
		params.OrderBy = "create_time"
	}
	if params.Desc == "" {
		params.Desc = "desc"
	}

	fmt.Printf("params: %#v\n", params)

	orderBy := fmt.Sprintf("%s %s", params.OrderBy, params.Desc)
	list, err := models.GetDynamicReplyByDynamicId(dynamicId, params.Page, params.Limit, orderBy)
	if err != nil {
		panic(err.Error())
	}
	type responseSuccess struct {
		ReplyId    int       `json:"reply_id"`
		Username   string    `json:"username"`
		Avatar     string    `json:"avatar"`
		Content    string    `json:"content"`
		CreateTime time.Time `json:"create_time"`
	}
	var replyList []responseSuccess
	for _, reply := range list {
		replyList = append(replyList, responseSuccess{
			ReplyId:    reply.Id,
			Content:    reply.Content,
			CreateTime: reply.CreateTime,
			Username:   reply.Username,
			Avatar:     utils.GetAvatar(reply.Avatar),
		})
	}
	response.Success(c, "获取成功", replyList)
}
